<template>
  <div class="users-view">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="用户名">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="filterForm.role" placeholder="全部角色" clearable class="role-select">
            <el-option label="管理员" value="admin" />
            <el-option label="运营" value="operator" />
            <el-option label="普通用户" value="customer_service" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleDisplayText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              link
              size="small"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total || 0"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="管理员" value="admin" />
            <el-option label="运营" value="operator" />
            <el-option label="普通用户" value="customer_service" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="400px"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPasswordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/services/api'

// 状态变量
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const resetPasswordDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])

// 表单引用
const userFormRef = ref(null)
const resetPasswordFormRef = ref(null)

// 过滤表单
const filterForm = reactive({
  username: '',
  role: '',
  status: ''
})

// 用户表单
const userForm = reactive({
  username: '',
  email: '',
  phone: '',
  role: 'operator',
  status: 1,
  password: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  userId: null,
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ]
}

const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户列表
const getUsers = async () => {
  loading.value = true
  try {
    // 使用分页接口，同时传递过滤条件
    const response = await api.get(`/user/page/${currentPage.value}/${pageSize.value}`, {
      params: {
        ...filterForm
      }
    })
    userList.value = response.data.data
    // 使用后端返回的总条数
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    admin: 'danger',
    operator: 'warning',
    customer_service: 'success'
  }
  return typeMap[role] || 'info'
}

// 角色显示文本
const getRoleDisplayText = (role) => {
  const textMap = {
    admin: '管理员',
    operator: '运营',
    customer_service: '普通用户'
  }
  return textMap[role] || role
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(userForm, {
    username: '',
    email: '',
    phone: '',
    role: 'operator',
    status: 1,
    password: ''
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 复制数据但排除密码字段，避免编辑时影响原始密码
  const { password, ...userData } = row
  Object.assign(userForm, userData)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/user/delete/${row.userId}`)
    ElMessage.success('删除成功')
    getUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 修改用户状态
const handleStatusChange = async (row) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1
    const actionText = newStatus === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${actionText}用户 "${row.username}" 吗？`,
      `确认${actionText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.put(`/user/update/${row.userId}`, {
      ...row,
      status: newStatus
    })
    
    ElMessage.success(`${actionText}成功`)
    getUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`操作失败`)
    }
  }
}

// 重置密码
const handleResetPassword = (row) => {
  resetPasswordForm.userId = row.userId
  resetPasswordForm.newPassword = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 提交重置密码
const handleResetPasswordSubmit = async () => {
  if (!resetPasswordFormRef.value) return
  
  try {
    await resetPasswordFormRef.value.validate()
    
    await api.put(`/user/update/${resetPasswordForm.userId}`, {
      password: resetPasswordForm.newPassword
    })
    
    ElMessage.success('密码重置成功')
    resetPasswordDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

// 提交用户表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      await api.post('/user/add', userForm)
      ElMessage.success('添加成功')
    } else {
      await api.put(`/user/update/${userForm.userId}`, userForm)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getUsers()
  } catch (error) {
    // 尝试从错误响应中提取具体的错误消息
    const errorMessage = error.response?.data?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败');
    ElMessage.error(errorMessage);
  }
}

//根据用户名获取用户
const getUserByUsername = async (username) => {
  try {
    const response = await api.get(`/user/name/${username}`);
    return response.data.data;
  } catch (error) {
    ElMessage.error('获取用户失败');
    return null;
  }
}

//根据角色获取用户
const getUsersByRole = async (role) => {
  try {
    const response = await api.get(`/user/role/${role}`);
    return response.data.data;
  } catch (error) {
    ElMessage.error('获取用户失败');
    return null;
  }
}

//根据状态获取用户
const getUsersByStatus = async (status) => {
  try {
    const response = await api.get(`/user/status/${status}`);
    return response.data.data;
  } catch (error) {
    ElMessage.error('获取用户失败');
    return null;
  }
}

// 过滤和分页
const handleFilter = async () => {
  currentPage.value = 1
  // 直接调用getUsers函数，它会使用分页API并传递过滤条件
  getUsers();
}

const resetFilter = () => {
  filterForm.username = ''
  filterForm.role = ''
  filterForm.status = ''
  handleFilter()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUsers()
}

// 初始加载
onMounted(() => {
  getUsers()
})
</script>

<style scoped>
.users-view {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 600;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}


.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  min-height: 40px;
  align-items: center;
}
</style>